<?php

namespace app\service;

use app\model\SystemSetting;
use app\traits\UserTrait;
use think\helper\Arr;

class SystemSettingService
{
    use UserTrait;

    /**
     * 默认取一条记录（仅允许存在一条）
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function read()
    {
        if (!$model = SystemSetting::where(['id' => 1])->find()) {
            return [
                'contact_mobile' => '',
                'intro_voice' => '',
                'image_forbidden' => '',
            ];
        }
        return [
            'contact_mobile' => Arr::get($model, 'contact_mobile', ''),
            'intro_voice' => Arr::get($model, 'intro_voice.url', ''),
            'image_forbidden' => Arr::get($model, 'image_forbidden.url', ''),
        ];
    }

    /**
     * 只获取一条
     * @return SystemSetting[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList()
    {
        return SystemSetting::order('id', 'desc')
            ->limit(1)
            ->with(['image_forbidden', 'intro_voice'])
            ->select();
    }

    /**
     * 新增和编辑只修改一条数据
     * @param array $data
     * @param $adminId
     * @return SystemSetting|array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function update(array $data, $adminId = 0)
    {
        $data['created_by'] = $this->getUid($adminId);
        if (!$model = SystemSetting::order('id', 'desc')->find()) {
            SystemSetting::create($data);
        } else {
            $model = SystemSetting::update($data, ['id' => $model->id]);
        }
        return $model;
    }
}